<template>
  <button
    type="button"
    class="msg-code-btn"
    :disabled="isDisabled"
    @click="getVerifyCode"
  >
    <span class="text">{{ text }}</span>
  </button>
</template>

<script lang="ts">
// lib
import { defineComponent } from "vue";
// components & widgets
// config
import { VERIFY_CODE } from "@/config/setting";
// script & utils & public
import { isMobile } from "@/utils/validator";
// controller & service & logic
import { getCodeService } from "@/biz/auth/service";
// interface
// 其它

export default defineComponent({
  name: "MsgCodeBtn",
  props: {
    mobile: String,
  },
  methods: {
    setTimer() {
      const changeCount = () => {
        if (this.count > 0) {
          this.count -= 1;
          this.text = `${this.count}S`;
        }
      };
      changeCount();
      this.timer = setInterval(() => {
        changeCount();
        if (this.count === 0 && this.timer) {
          clearInterval(this.timer);
          this.timer = undefined;
          this.count = VERIFY_CODE.INTERVAL_TIME;
          this.text = "发送验证码";
        }
      }, 1000);
    },
    async getVerifyCode() {
      if (!this.mobile || !isMobile(this.mobile)) {
        this.$toast.fail("手机号格式错误");
        return;
      }
      this.setTimer();
      const result = await getCodeService(this.mobile);
      // 成功
      if (result.payload) {
        this.$toast.success("验证码已发送");
      }
    },
  },
  data() {
    const data: {
      timer: number | undefined;
      count: number;
      text: string;
    } = {
      timer: undefined,
      count: VERIFY_CODE.INTERVAL_TIME,
      text: "发送验证码",
    };
    return data;
  },
  computed: {
    isDisabled() {
      return (
        !isMobile(this.mobile || "") || this.count !== VERIFY_CODE.INTERVAL_TIME
      );
    },
  },
});
</script>

<style lang="less">
.msg-code-btn {
  width: 180px;
  height: 90px;
  overflow: hidden;

  .text {
    color: @color-primary;
    font-size: 30px;
  }
}
</style>
